
package com.hyst.seviceImpl;

import com.google.common.collect.Maps;
import com.hyst.common.ResultBean;
import com.hyst.domain.*;
import com.hyst.repository.PurchaseCourseMapper;
import com.hyst.repository.PurchaseCourseViewMapper;
import com.hyst.repository.RecommendMsgMapper;
import com.hyst.repository.StudentMapper;
import com.hyst.service.CurriculumScheduleService;
import com.hyst.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hyst.repository.TrylistenmanageMapper;
import com.hyst.service.TrylistenmanageService;
import com.hyst.utils.UuidTool;

import java.util.*;

@Service
public class TrylistenmanageServiceImpl implements TrylistenmanageService {

    private static final List<String> PE= Arrays.asList("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");

    @Autowired
    private TrylistenmanageMapper mapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private PurchaseCourseViewMapper courseMapper;

    @Autowired
    private CurriculumScheduleService curriculumScheduleService;

    @Autowired
    private RecommendMsgMapper recommendMsgMapper;

    @Override
    public Page<TrylistenmanageView> list(final TrylistenmanageView trylistenmanage) {
        final Page<TrylistenmanageView> page = PageHelper.startPage(trylistenmanage.getPageNum(), trylistenmanage.getPageSize());
        //mapper.select(trylistenmanage);

        if (StringUtils.isNotBlank(trylistenmanage.getStudentId())) {
            if ("all".equals(trylistenmanage.getStudentId())) {
                trylistenmanage.setStudentId(null);
            }
        }

        if (StringUtils.isNotBlank(trylistenmanage.getNowState())) {
            if ("1".equals(trylistenmanage.getNowState())) {
                trylistenmanage.setNowState("进行中");
            } else if ("2".equals(trylistenmanage.getNowState())) {
                trylistenmanage.setNowState("已完成");
            }
        }

        if (StringUtils.isNotBlank(trylistenmanage.getTrylistenType())) {
            if ("1".equals(trylistenmanage.getTrylistenType())) {
                trylistenmanage.setTrylistenType("新试听");
            } else if ("2".equals(trylistenmanage.getTrylistenType())) {
                trylistenmanage.setTrylistenType("二次试听");
            }
        }

        if (StringUtils.isNotBlank(trylistenmanage.getFollowUp())) {
            if ("1".equals(trylistenmanage.getFollowUp())) {
                trylistenmanage.setFollowUp("正式报课");
            } else if ("2".equals(trylistenmanage.getFollowUp())) {
                trylistenmanage.setFollowUp("不报课");
            }
        }

        mapper.getAll(trylistenmanage);

        for(TrylistenmanageView trylistenmanageView:page.getResult()){
            Map<String,String> sqlMap = new HashMap<>();
            sqlMap.put("lessionId",trylistenmanageView.getCourse());
            sqlMap.put("leveId",trylistenmanageView.getCourseLevel());
            String lesson = courseMapper.getLesson(sqlMap);
            trylistenmanageView.setCourseName(lesson);
        }
        return page;
    }

    @Override
    public Page<TrylistenmanageView> selectByCondition(final TrylistenmanageView trylistenmanage, String selectCondition) {
        final Page<TrylistenmanageView> page = PageHelper.startPage(trylistenmanage.getPageNum(), trylistenmanage.getPageSize());
        if (StringUtils.isNotBlank(selectCondition)) {
            try {
                mapper.getAllCond(selectCondition);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            TrylistenmanageView trylistenmanageView = new TrylistenmanageView();
            mapper.getAll(trylistenmanageView);
        }
        return page;
    }

    @Override
    public Trylistenmanage insert(final Trylistenmanage trylistenmanage) {
        trylistenmanage.setUniqueId(UuidTool.randomUUID());
        if (StringUtils.isNotBlank(trylistenmanage.getTrylistenType())) {
            if ("1".equals(trylistenmanage.getTrylistenType())) {
                trylistenmanage.setTrylistenType("二次试听");
            } else if ("0".equals(trylistenmanage.getTrylistenType())) {
                trylistenmanage.setTrylistenType("新试听");
            }
        }
        Student stuInfo = studentMapper.getById(trylistenmanage.getStudentId());
        if (stuInfo != null) {
            if(StringUtils.isNotBlank(stuInfo.getZoomId())){
                trylistenmanage.setZoomId(stuInfo.getZoomId());
            }
            if (null != stuInfo.getAge()) {
                trylistenmanage.setAge(stuInfo.getAge());
            }
            //课程
            if (StringUtils.isNotBlank(stuInfo.getRecommend())) {
                trylistenmanage.setRecommand(stuInfo.getRecommend());
            }
        }
        if(StringUtils.isNotBlank(trylistenmanage.getAuditionTime())){
            trylistenmanage.setAuditionDate(trylistenmanage.getAuditionTime().split(",")[0].trim());
            int count = 0;
            String counStr = trylistenmanage.getAuditionTime().split(",")[1].trim();
            char[] c = counStr.toCharArray();
            for (int i = 0; i < c.length; i++) {
                String cstr = String.valueOf(c[i]);
                if ("-".equals(cstr)) {
                    count++;
                }
            }
            trylistenmanage.setHoursEnrolled(count);
        }
        mapper.insertSelective(trylistenmanage);

        // 将试听时间插入排课表中
        if (StringUtils.isNotBlank(trylistenmanage.getAuditionTime())) {
            try {
                //2018-12-17 , Monday 20:30-20:45 20:45-21:00
                String week = trylistenmanage.getAuditionTime().split(",")[1].trim().split(" ")[0].trim();
                int weekId = PE.indexOf(week) + 1;
                String classBegin = trylistenmanage.getAuditionTime().split(",")[1].trim().split(" ")[1].trim().split("-")[0].trim();
                String[] split = trylistenmanage.getAuditionTime().split(",")[1].trim().split(" ");
                String classEnd = split[split.length - 1].split("-")[1].trim();

                CurriculumSchedule curriculumSchedule = new CurriculumSchedule();
                curriculumSchedule.setPurchaseCourseId("0");
                curriculumSchedule.setClassDate(DateUtils.parseDate(trylistenmanage.getAuditionDate(), "yyyy-MM-dd"));
                curriculumSchedule.setClassWeek(weekId);
                curriculumSchedule.setClassTime(classBegin);
                curriculumSchedule.setClassTimeEnd(classEnd);
                curriculumSchedule.setClassLength(trylistenmanage.getHoursEnrolled() * 15);
                if (StringUtils.isNotBlank(trylistenmanage.getCourse()) && !"请选择".equals(trylistenmanage.getCourse())) {
                    curriculumSchedule.setMaterial(trylistenmanage.getCourse());
                }
                if (StringUtils.isNotBlank((trylistenmanage.getCourseLevel())) && !"请选择".equals(trylistenmanage.getCourseLevel())) {
                    curriculumSchedule.setMaterialLevel(Integer.valueOf(trylistenmanage.getCourseLevel()));
                }
                if (StringUtils.isNotBlank(trylistenmanage.getTeacherId()) && !"请选择".equals(trylistenmanage.getTeacherId())) {
                    curriculumSchedule.setTeacherId(trylistenmanage.getTeacherId());
                }
                if (StringUtils.isNotBlank(trylistenmanage.getStudentId()) && !"请选择".equals(trylistenmanage.getStudentId())) {
                    curriculumSchedule.setStudentId(trylistenmanage.getStudentId());
                }
                if (StringUtils.isNotBlank(trylistenmanage.getUniqueId())) {
                    curriculumSchedule.setPurchaseCourseId(trylistenmanage.getUniqueId());
                }
                curriculumSchedule.setState(0);
                curriculumSchedule.setType("tryListern");
                curriculumScheduleService.insert(curriculumSchedule);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return trylistenmanage;
    }

    @Override
    public Trylistenmanage getByPriKey(final Integer id) {
        final Trylistenmanage trylistenmanage = mapper.selectByPrimaryKey(id);
        return trylistenmanage;
    }

    @Override
    public Trylistenmanage updateSelective(final Trylistenmanage trylistenmanage) {
        mapper.updateByPrimaryKeySelective(trylistenmanage);
        return trylistenmanage;
    }

    @Override
    public Trylistenmanage update(final Trylistenmanage trylistenmanage) {
        if (StringUtils.isNotBlank(trylistenmanage.getAuditionTime())) {
            trylistenmanage.setAuditionDate(trylistenmanage.getAuditionTime().split(",")[0].trim());

            int count = 0;
            String counStr = trylistenmanage.getAuditionTime().split(",")[1].trim();
            char[] c = counStr.toCharArray();
            for (int i = 0; i < c.length; i++) {
                String cstr = String.valueOf(c[i]);
                if ("-".equals(cstr)) {
                    count++;
                }
            }
            trylistenmanage.setHoursEnrolled(count);
        }
        mapper.updateInfo(trylistenmanage);
        return trylistenmanage;
    }

    @Override
    public Trylistenmanage delete(final Integer id) {

        return null;
    }

    @Override
    public Trylistenmanage saveRemark(final String uniqueId) {
        System.out.println(uniqueId);
        String[] a = uniqueId.split("&");
        Trylistenmanage entity = new Trylistenmanage();
        entity.setUniqueId(a[0]);
        entity.setFollowUp(a[1]);
        if (!a[2].equals("extra")) {
            entity.setRemark(a[2].replace("extra", ""));
        }

        //释放保留课时间
        if ("不报课".equals(entity.getFollowUp()) || "正式报课".equals(entity.getFollowUp())) {
            String student = mapper.selectDate(entity.getUniqueId());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(student)) {
                mapper.deleteFormal(student);
                mapper.savePerTime(entity);
            }

            final Map recommend = studentMapper.getRecommend(student);
            final HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
            objectObjectHashMap.put("studentId",recommend.get("studentId"));
            objectObjectHashMap.put("recommender",recommend.get("recommend"));
            objectObjectHashMap.put("status", null);
            if (recommend.get("recommend") != null) {
                recommendMsgMapper.updateStatus(objectObjectHashMap);
            }
        }
        mapper.saveRemarkData(entity);
        return null;
    }

    @Override
    public Trylistenmanage savestateEdit(final String postMsg) {
        try {
            System.out.println(postMsg);
            String[] a = postMsg.split("&");
            Trylistenmanage entity = new Trylistenmanage();
            entity.setUniqueId(a[0]);
            entity.setNowState(a[1]);

            if ("已完成".equals(entity.getNowState())) {
                TrylistenmanageView trylistenmanageView = new TrylistenmanageView();
                trylistenmanageView.setUniqueId(entity.getUniqueId());
                TrylistenmanageView byUidData = mapper.getByUidData(trylistenmanageView);
                if (byUidData != null && StringUtils.isNotBlank(byUidData.getAuditionTime())) {
                    String time = byUidData.getAuditionTime().split(",")[0];
                    Date authTime = DateUtils.parseDate(time.trim());

                    Date now = new Date();
                    if (now.before(authTime)) {
                        return null;
                    } else {
                        mapper.savestateEditData(entity);
                    }
                }
            }

            //释放试听课
            if (StringUtils.isNotBlank(a[1])) {
                String studentId = mapper.getStudentId(Long.valueOf(a[0]));
                if (StringUtils.isNotBlank(studentId)) {
                    mapper.deleteFree(studentId);
//				mapper.saveAuditionTime(entity);
                }
            }
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Trylistenmanage savedoDelete(final String uniqueId) {
        System.out.println(uniqueId);
        Trylistenmanage entity = new Trylistenmanage();
        entity.setUniqueId(uniqueId);
        entity.setIsdeleted(1);
        mapper.savedoDeleteData(entity);

        //释放时间
        mapper.deleteDataTime(entity);
        return null;
    }

    @Override
    public TrylistenmanageView getByUid(final String uniqueId) {
        System.out.println(uniqueId);
        TrylistenmanageView entity = new TrylistenmanageView();
        entity.setUniqueId(uniqueId);
        final TrylistenmanageView outentity = mapper.getByUidData(entity);
        System.out.println(outentity);
        return outentity;
    }

    @Override
    public Page<TrylistenmanageView> getByConditon(final TrylistenmanageView trylistenmanage, final String conditiontest) {
        final Page<TrylistenmanageView> page = PageHelper.startPage(trylistenmanage.getPageNum(), trylistenmanage.getPageSize());
        TrylistenmanageView entity = new TrylistenmanageView();
        entity.setEnName(conditiontest);
        mapper.getListByConditon(entity);
        return page;
    }

    public ResultBean getFuzerenId(String studentId) {
        try {
            return ResultBean.success(mapper.getfuzerenId(studentId).getFuzerenId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBean.fail("");
    }

    @Override
    public Trylistenmanage getReportData(Integer id){
        try {
            Trylistenmanage reportData = mapper.getReportData(id);
            String enName = mapper.getEnName(reportData.getStudentId());
            if(StringUtils.isNotBlank(enName)){
                reportData.setStudentId(enName);
            }
            return reportData;
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
